package com.suneee.base.util;

import java.io.IOException;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.suneee.base.config.ServiceConfig;
import com.suneee.base.util.ContextHelper;
import com.suneee.core.util.DateUtils;
import com.suneee.core.util.StringUtils;

public class HttpClientUtils {

	private static final Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);

//	private static final String WXDEV_SERVER_URL = "http://wxtest.weilian.cn/b2b.php?m=b2b&c=data&a=";
	
	//	private static final String WXDEV_SERVER_URL = "http://wxdev.weilian.cn/b2b.php?m=b2b&c=data&a=";

	/**
	 * 发送 post（json）
	 *          请求访问
	 * @param method 
	 *        方法名称 例如： productLineSyc
	 * @param jsonData
	 *         json数据
	 * @param url
	 *         	商城URL
	 * @return 请求返回数据
	 * @throws IOException
	 */
	public static String postJson(String method, String jsonData,String url) throws IOException {
		String result = null;
		HttpEntity respEntity = null;
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		try {
			HttpEntity reqEntity = null;
			if (jsonData != null) {
				reqEntity = new ByteArrayEntity(jsonData.getBytes("UTF-8"), ContentType.APPLICATION_JSON);
			}
			httpclient = HttpClients.createDefault();

			if(!StringUtils.isBlank(url)){
				HttpPost httppost = new HttpPost(url + method);
				RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(30000)
						.setConnectTimeout(30000).setConnectionRequestTimeout(30000).setStaleConnectionCheckEnabled(true)
						.build();
				httppost.setConfig(defaultRequestConfig);
				if (reqEntity != null) {
					httppost.setEntity(reqEntity);
				}

				response = httpclient.execute(httppost);
				if (200 != response.getStatusLine().getStatusCode()) {// 失败
					logger.error("Receive http response:" + response.getStatusLine().getStatusCode());
					return "{\"is_success\":false,\"error_code\":\"" + response.getStatusLine().getStatusCode()
							+ "\",\"message\":\"翌商城服务器连接失败\"}";
				}
				respEntity = response.getEntity();
				if (respEntity != null) {
					result = EntityUtils.toString(respEntity, "UTF-8");
					logger.info("Receive http response:"+result);
				}
			}
		} finally {
			EntityUtils.consume(respEntity);
			close(response, httpclient);
		}
		return result;
	}
	
	/**
	 * 关闭http请求及返回
	 * 
	 * @param response
	 * @param httpclient
	 */
	private static void close(CloseableHttpResponse response, CloseableHttpClient httpclient) {
		if (response != null) {
			try {
				response.close();
			} catch (IOException e) {
			}
		}
		if (httpclient != null) {
			try {
				httpclient.close();
			} catch (IOException e) {
			}
		}
	}
	
	
	public static void main(String[] args) {
//		String pdLinejson = "{\"lines\":[{\"code\":\"01\",\"pcode\":\"\",\"name\":\"产品线AAA\",\"is_del\":\"0\",\"order\":\"1\"}]}";
//		String goodsJson ="{"
//				+ "\"products\":["
//				+ "{"
//				+ "\"goods_code\":\"10799\","
//				+ "\"enterprise_code\":\"qy20161102662\","
//				+ "\"brand_code\":\"1\","
//				+ "\"title\":\"2016优衣库秋季针织衫\","
//				+ "\"line_code\":\"01\","
//				+ "\"category_code\":\"0103\","
//				+ "\"spu_data\":\"\","
//				+ "\"about\":\"2016优衣库秋季新款针织衫\","
//				+ "\"detail\":\"Heilan Home/海澜之家2016秋季新品男装简约V领套头长袖针织衫男\","
//				+ "\"images\":\"1.jpg,2.jpg\","
//				+ "\"market_price\":\"168.00\","
//				+ "\"retail_price\":\"199.00\","
//				+ "\"batch_price\":\"199.00\","
//				+ "\"batch_retail_price\":\"199.00\","
//				+ "\"max_price\":\"199.00\","
//				+ "\"min_price\":\"179.00\","
//				+ "\"sku_specify\":["
//						+ "{\"code\":\"68\",\"name\":\"尺码\",\"values\":[{\"id\":\"68_01\",\"value\":\"170/88A\"},{\"id\":\"68_02\",\"value\":\"175/92A\"}]},"
//						+ "{\"code\":\"69\",\"name\":\"颜色\",\"values\":[{\"id\":\"69_01\",\"value\":\"青色\"},{\"id\":\"69_02\",\"value\":\"黄色\"}]}"
//							   + "],"
//				+ "\"property_specify\":\"\","
//				+ "\"stock\":100,"
//				+ "\"sku_list\":["
//						+ "{"
//							+ "\"sku_id\":10799001,\"stock\":50,\"batch_price\":179.00,\"retail_price\":199.00,"
//							+ "\"specify\":["
//								   + "{\"code\":\"68\",\"value_code\":\"170/88A\"},"
//								   + "{\"code\":\"69\",\"value_code\":\"青色\"}"
//								   + "]"
//						+ "},"
//						+ "{"
//						+ "\"sku_id\":10799002,\"stock\":50,\"batch_price\":179.00,\"retail_price\":199.00,"
//								+ "\"specify\":["
//											+ "{\"code\":\"68\",\"value_code\":\"175/92A\"},"
//											+ "{\"code\":\"69\",\"value_code\":\"黄色\"}"
//										  + "]"
//						+ "}]"
//			    + "}]}";
//		
//		String brandJson = "{\"lines\":[{\"code\":\"2\",\"name\":\"比亚迪\",\"owner\":\"比亚蒂\",\"categorys\":\"03,04,05,02\",\"icon_file\":\"\",\"sort\":\"\",\"is_del\":\"0\"}]}";
		
		String categoryJson = "{\"lines\":[{\"code\":\"0102\",\"pcode\":\"01\",\"name\":\"潮流女装\",\"sort\":\"\",\"is_del\":\"0\"}]}";
		
//		try {
//			String pdLineStr = postJson("productLineSyc", json);
//			String goodStr = postJson("goodsSyc", goodsJson);
//			String brandStr = postJson("brandSyc", brandJson);
//			String cateStr = postJson("categorySyc", categoryJson);
		
//			System.out.println("接口返回数据："+cateStr);
		
			
			System.out.println(DateUtils.getTimestamp(new Date()));
			
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
	}
}
